<!-- 客户分组 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <div class="top topSubmitBtn">
        <el-button class="btn" type="primary" @click="addDepartment()" >添加分组</el-button>
      </div>
      <div>
        <el-table 
          border 
          :data="tableData" 
          style="width: 100%; margin: 15px 0" 
          row-key="ID"  
          default-expand-all 
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column prop="date" type="index" label="序号" width="80" align="left"></el-table-column>
          <el-table-column prop="DepartmentName" label="分组名称" ></el-table-column>
          <el-table-column label="操作" align="left" width="180px">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleAdd(scope.row)">添加分组</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="添加分组"
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="30%">
      <el-form label-width="100px" :model="grouForm" :rules="rules" ref="grouForm">
        <el-form-item label='上级分组:'>
          <el-cascader
            ref="clientgroup"
            style="width:100%;"
            v-model="grouForm.lastDepartmemt"
            placeholder="请选择分组，若空则为根分组"
            clearable
            :options="CustomerList"
            :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'DepartmentName', value: 'DepartmentName'}"
            @visible-change="groupOnlick"
            @expand-change="groupOnlick"
            >
          </el-cascader>
        </el-form-item>
        <el-form-item label='分组名称:' prop="DepartmentName">
          <el-input v-model="grouForm.DepartmentName" maxlength="16"  show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from "@/api/firstPage";
import Cookies from 'js-cookie'
import { treeing, getTreeData } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      dialogVisible: false,
      grouForm:{},
      options:[],
      tableData: [],
      CustomerList:[],
      rules:{
        DepartmentName: [
          { required: true, message: '分组名称不能为空' },
          { min: 1, max: 16, message: '分组名称不能超过 16 个字符', trigger: 'blur' }
        ],
      }
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    this.getData()
    this.GetCustomerClass()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    async getData(){
      const res = await connrequest('GetCustomerClass')
      let arr = getTreeData(this.treeing(res.Data,'DepartmentName','ParentName'))
      // let arr = res.Data
      this.tableData = arr
    },
    async GetCustomerClass(){
      // const res = await connrequest('GetCustomerClass')
      const res = await connrequest('GetCustomerClass')
      let arr = []
      this.CustomerList = getTreeData(this.treeing(res.Data,'DepartmentName','ParentName'))
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push(item.DepartmentName)
      })
      this.allgroupList = arr  //所有分组放到数组里
    },
    treeing(arr, id, parentid) {
      let tree = []
      const map = {}
      for (let item of arr) {
        // 一个新的带children的结构
        let newItem = map[item.DepartmentName] = {
          ...item,
          children: []
        }
        if (map[item.ParentName]) { // 父节点已存进map则在父节点的children添加新元素
          let parent = map[item.ParentName]
          parent.children.push(newItem)
        } else { // 没有父节点，在根节点添加父节点
          tree.push(newItem)
        }
      }
      return tree
    },
    addDepartment(){
      this.grouForm = {}
      this.ParentID = 0
      this.ParentName = []
      this.options = this.tableData
      this.$nextTick(()=>{
        this.$refs['grouForm'].clearValidate()
      })
      this.dialogVisible = true
    },
    handleAdd(item){
      this.options = this.tableData
      this.grouForm = {}
      this.$set(this.grouForm, 'lastDepartmemt', item.DepartmentName)
      this.$nextTick(()=>{
        this.$refs['grouForm'].clearValidate()
      })
      this.dialogVisible = true
    },
    // 级联选项卡点击关闭下拉
    elCascaderOnlick(){
      let that = this;
      setTimeout(function() {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function() {
            this.previousElementSibling.click();
            that.$refs.cascaderAddr.dropDownVisible = false;
          };
        });
      }, 100);
    },
    // 级联选项卡点击关闭下拉
    groupOnlick(){
      let that = this;
      setTimeout(function() {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function() {
            this.previousElementSibling.click();
            that.$refs.clientgroup.dropDownVisible = false;
          };
        });
      }, 100);
    },
    handleChange(item){
      if(item){
        this.DepartmentName  = item[item.length - 1]
        this.ParentName = this.$refs['cascaderAddr'].getCheckedNodes()[0].level === 1 ? '' : this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels[0]
      }
    },
    async submit(){
      this.$refs['grouForm'].validate( async(valid) => {
        if(valid){
          let ParentName = this.$refs['clientgroup'].getCheckedNodes()[0]?.value || ''
          const params = {
            Paging:{
              QueryPageNo: 1,
              QueryPageLength: 10
            },
            Filter:{
              Group: ParentName
            }
          }
          const CustomerRes = await connrequest('GetCustomer', params)
          if (CustomerRes.Data.length > 0 && ParentName !== '') {
            this.$message.error(`${ParentName}分组下存在客户，请删除${ParentName}下的所有客户后操作`);
            return false
          }
          if(this.allgroupList.indexOf(this.grouForm.DepartmentName) !== -1){
            this.$message.error('该分组已经存在')
          }else{
            const data = { 
              Data:{
                DepartmentName: this.grouForm.DepartmentName,
                ParentName: ParentName
              }
            }
            const res = await connrequest('AddCustomerClass', data)
            if(res.Status.StatusCode === 0){
              this.$message({
                type: 'success',
                message: '分组添加成功'
              });
              this.getData()
              this.GetCustomerClass()
              this.dialogVisible = false
            }
          }
        }
      })
    },
    async handleDelete(data){
      const params = {
        Paging:{
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
      }
      const res = await connrequest('GetCustomer', params)
      let arr = res.Data.filter(item => {return item.BelongGroup === data.DepartmentName})
      if(data.children !== undefined){
        this.$message.error('该分组下还存在其他分组')
      }else if(arr.length > 0){
        this.$message.error('该分组下还有客户,无法删除')
      }else{
        let DepartmentName = data.DepartmentName
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = {
            Data:{
              DepartmentName:DepartmentName,
            }
          }
          const res = await connrequest('DelCustomerClass', data)
          if(res.Status.StatusCode === 0){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getData()
            this.GetCustomerClass()
            this.dialogVisible = false
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    }
  }
};
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>